<template>
	<div class="underway-project-content custom-scrollbar">
		<template v-if="!notProject">
			<project-admin-list :projectList="underWayProjects" :curProjectIndex="curProjectIndex" @handleSelectProject="handleSelectProject">
			</project-admin-list>
			<view class="project-content">
				<view class="p_c-header">
					<project-admin-navbar :projectList="underWayProjects" :relevanceUserID="relevanceUserID" :curProjectIndex="curProjectIndex"
					 @handleProject="handleEditProject">
					 </project-admin-navbar>
				</view>
				<view class="p_c-body">
					<template v-if="underWayProjects.length > 0">
						<project-admin-body :projectList="underWayProjects" :relevanceUserID="relevanceUserID" :curProjectIndex="curProjectIndex"
						 @showMyProjectModule="showMyProjectModule" @handleUploadModule="handleUploadModule" @handleDownLoadModule="handleDownLoadModule"
						 @handleRemoveModule="handleRemoveModule">
						 </project-admin-body>
					</template>
				</view>
			</view>

			<!-- 查看队友负责的项目模块 -->
			<el-drawer :title="curUserData.username" :visible.sync="drawer" direction="ltr">
				<el-tree :data="curUserData.burdenModule" default-expand-all></el-tree>
			</el-drawer>

			<!-- 上传文档模块 -->
			<el-dialog title="上传文档模块" :before-close="beforeCloseDialog" :visible.sync="dialogVisible" width="60%">
				<!-- 自己负责模块的名称（文档名称） -->
				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="模块名称" prop="fileName">
						<el-input placeholder="该名称必须唯一" disabled v-model="ruleForm.fileName"></el-input>
					</el-form-item>
					<el-form-item style="margin-top: 60px;" label="模块文档" prop="fileUrl">
						<el-upload class="upload-demo" action="" :file-list="fileList" :limit="1" accept=".doc,.docx,.pdf,.xlsx,.xls"
						 :http-request="uploadFile" drag ref="uploadModule" :on-exceed="handleExceed">
							<i class="el-icon-upload"></i>
							<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
							<div class="el-upload__tip" slot="tip">只能上传doc/docx/pdf/xlsx/xls,且不超过100M</div>
						</el-upload>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer">
					<el-button type="primary" @click="uploadDocModule('ruleForm')">确认上传</el-button>
				</span>
			</el-dialog>
		</template>
		<template v-if="notProject">
			<el-alert :closable="false" title="提示" type="warning" description="您没有正在进行的项目,请先去编辑项目,项目管理-->编辑项目" show-icon>
			</el-alert>
		</template>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import alioss from "@/common/aliyun.oss.client.js";
	const rules = {
		fileName: [{
			required: true,
			message: '你负责的模块文档的名称（注意这个·名称必须唯一·,自动获取您上传文档的名称），建议为（项目简写+自己姓名或者昵称+负责模块自定义名称）。如需要修改名称,请先删除该模块,再重新上传',
			trigger: 'blur'
		}, ],
		fileUrl: [{
			required: true,
			message: '请选择要上传的模块',
			trigger: 'blur'
		}]
	}
	export default {
		data() {
			return {
				notProject: false,
				curUserData: {}, //当前用户的信息
				drawer: false,
				underWayProjects: [],
				curProjectIndex: 0,
				curProjectData: {},
				rules,
				ruleForm: {
					fileName: '',
					fileUrl: "",
				},
				dialogVisible: false,
				fileList: [] //上传文件的列表
			}
		},
		computed: {
			...mapState(['relevanceUserID'])
		},
		watch: {
			relevanceUserID(newVal, oldVal) { // 由于刷新需要验证token所有可能ID重新存储了
				this.getCurPageData()
			}
		},
		created() {
			if (this.relevanceUserID !== -1) this.getCurPageData()
		},
		methods: {
			...mapMutations(['createProject', 'setEditProjectID']),
			async getCurPageData() {
				let {
					relevanceUserID
				} = this;
				this.notProject = false;
				let res = await this.$network({
					api: "getUnderwayProject",
					data: {
						relevanceUserID
					}
				})
				if (res.status === 0) {
					this.underWayProjects = res.data;
				}
				if (res.status === 1) {
					this.notProject = true;
				}
			},
			handleSelectProject(item, index) {
				this.curProjectIndex = index;
				this.curProjectData = item;
			},
			// 仅负责人可编辑
			handleEditProject() {
				let {
					underWayProjects,
					curProjectIndex,
					relevanceUserID
				} = this;
				if (underWayProjects[curProjectIndex].relevanceUserID === relevanceUserID) {
					Object.keys(underWayProjects[curProjectIndex]).forEach(key => {
						this.createProject({
							key,
							val: underWayProjects[curProjectIndex][key]
						});
					})
					this.$router.push('/project_admin/create');
				} else {
					this.$message({
						message: '同学您不是负责人，不可以编辑项目！',
						type: 'warning'
					});
				}
			},
			showMyProjectModule(item, index) {
				this.drawer = true;
				this.curUserData = item;
			},
			handleUploadModule(item, index) {
				this.curUserData = item;
				this.dialogVisible = true;
				let {
					fileName,
					fileUrl
				} = item.finishProjectDoc;
				if (fileName !== "" && fileUrl !== "") {
					this.ruleForm.fileName = fileName;
				}
			},
			// 文件超出限制
			handleExceed(e) {
				this.$message.warning('亲，一次只能上传一个文件哦')
			},
			// 删除模块
			handleRemoveModule(item, index) {
				let {
					curProjectIndex,
					underWayProjects
				} = this;
				let {
					fileName,
					fileUrl
				} = item.finishProjectDoc;
				if (fileName === "") {
					this.$message.warning("您还没有上传自己负责的项目模块")
					return false;
				}

				this.$alert('确认删除吗。删除后无法恢复？', '提示', {
					confirmButtonText: '取消',
					showCancelButton: true,
					cancelButtonText: "删除",
					type: "warning",
					callback: async action => {
						if (action === 'cancel' || action === "close") {
							let loading = this.$loading({
								lock: true,
								text: '正在删除',
								spinner: 'el-icon-loading'
							});
							//删除文档
							let aliossDelete = await alioss.deleteFile(fileName);

							//删除module_key
							let deleteKey = await uniCloud.callFunction({
								name: "deleteModuleKey",
								data: {
									fileName
								}
							})

							//删除用户存储的数据
							let deleteModuleOptions = await uniCloud.callFunction({
								name: "deleteModuleOptions",
								data: {
									projectID: underWayProjects[curProjectIndex]._id,
									userID: item.userID,
								}
							})
							loading.close();
							if (deleteKey.result.status == 0 && deleteModuleOptions.result.status == 0) {
								this.$message({
									message: '删除成功',
									type: 'success'
								});
								this.getCurPageData() // 更新数据
							}
						}
					}
				})
			},
			// 存储当前模块到数据库
			uploadDocModule(formName) {
				let {
					curUserData,
					curProjectIndex,
					underWayProjects,
					ruleForm
				} = this;
				let data = {
					projectID: underWayProjects[curProjectIndex]._id,
					userID: curUserData.userID,
					fileName: ruleForm.fileName,
					fileUrl: ruleForm.fileUrl,
					time: Date.now()
				}
				this.$refs[formName].validate(async (valid) => {
					if (valid) {

						/**
						 * 更新消息提示
						 */
						// let partnerChangeUploadModule = {
						// 	time:Date.now(),
						// 	projectID:underWayProjects[curProjectIndex]._id,
						// 	userID:curUserData.userID,
						// 	fileName: ruleForm.fileName
						// }

						let res = await this.$network({
							api: "saveModuleOptiions",
							data
						})

						if (res.status === 0) {
							this.$message({
								message: '上传成功',
								type: 'success'
							});
							this.$refs.ruleForm.resetFields();
							this.$refs.uploadModule.clearFiles();
							this.dialogVisible = false;
							this.getCurPageData() // 更新数据
						}
					} else {
						return false;
					}
				})
			},
			beforeCloseDialog(done) {
				this.$alert('确认放弃上传吗？，将会清空您的选择？', '提示', {
					confirmButtonText: '继续上传',
					showCancelButton: true,
					cancelButtonText: "放弃上传",
					type: "warning",
					callback: action => {
						if (action === 'cancel' || action === "close") {
							this.$refs.ruleForm.resetFields();
							this.$refs.uploadModule.clearFiles();
							done()
						}
					}
				})
			},
			//上传
			async uploadFile(params) {
				let _file = params.file;
				let isLt100M = (_file.size / 1024 / 1024) < 100;
				this.fileList = [];

				if (!isLt100M) {
					this.$message.warning("请上传100M以下的doc/docx/pdf/xlsx/xls文件")
					return false;
				}

				//校验文件名是否重复（仅在没有上传过模块的情况下校验）
				let {
					curUserData
				} = this;
				let {
					fileName,
					fileUrl
				} = curUserData.finishProjectDoc;
				if (fileName === "" && fileUrl === "") {
					const loading = this.$loading({
						lock: true,
						text: '正在校验文件名是否重复',
						spinner: 'el-icon-loading'
					});
					let checkRes = await uniCloud.callFunction({
						name: "checkModuleKey",
						data: {
							fileName: _file.name
						}
					})

					loading.close();
					if (checkRes.result.status !== 0) {
						this.$refs.ruleForm.validateField('fileName')
						return false;
					}
				} else {
					//检验当前更新的文档名称是否和用户的一样
					if (_file.name !== fileName) {
						this.$alert('亲我们检测到，您已经保存的文档名称和现在更新的不同，请重新上传！', '提示', {
							type: "error",
							confirmButtonText: '确定',
							callback: action => {
								this.$refs.ruleForm.validateField('fileName')
							}
						});
						return false
					}
				}

				let aliossUploadRes = await alioss.put(_file, _file.name);
				let {
					name,
					url
				} = aliossUploadRes;
				this.fileList.push({
					name,
					url
				});
				this.ruleForm.fileName = name;
				this.ruleForm.fileUrl = url;
				this.$refs.ruleForm.validateField('fileName');
			},
			handleDownLoadModule(item, index) {
				if (item.finishProjectDoc.fileName === "") {
					this.$message.warning("该队友还没有上传项目模块")
					return false;
				}
				let downloadUrl = alioss.getDownloadUrl(item.finishProjectDoc.fileName);
				window.open(downloadUrl);
			}
		}
	}
</script>

<style lang="scss">
	.underway-project-content {
		height: 100%;

		.project-content {
			margin-top: 20px;

			.p_c-header {
				@include f-ai-jc(flex, center, flex-end)
			}
		}
	}
</style>
